package controllers

import (
	"beego_background_framework/models"
	"encoding/json"
	"github.com/gorilla/websocket"

	"fmt"
	"net/http"
)

// ChatController operations for Chat
type ChatController struct {
	BaseController
}

// Get method handles GET requests for ChatController.
func (c *ChatController) Index() {
	user := c.GetSession("admin_user")
	//fmt.Println(user.(*models.AdminUser).Username)
	//var user = models.AdminUser{}
	//user = c.GetSession("admin_user")
	c.Data["IsWebSocket"] = true
	c.Data["UserName"] = user.(*models.AdminUser).Username

	//展示
	c.SetTpl("chat/websocket.html")
}

func (c *ChatController) Socket() {
	uname := c.GetSession("admin_user").(*models.AdminUser).Username

	// Upgrade from http request to WebSocket.
	ws, err := websocket.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(c.Ctx.ResponseWriter, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		fmt.Errorf("Cannot setup WebSocket connection:", err)
		return
	}

	// Join chat room.
	Join(uname, ws)
	defer Leave(uname)

	// Message receive loop.
	for {
		_, p, err := ws.ReadMessage()
		if err != nil {
			return
		}
		publish <- newEvent(models.EVENT_MESSAGE, uname, string(p))
	}
}

// broadcastWebSocket broadcasts messages to WebSocket users.
func broadcastWebSocket(event models.Event) {
	data, err := json.Marshal(event)
	if err != nil {
		fmt.Errorf("Fail to marshal event:", err)
		return
	}

	for sub := subscribers.Front(); sub != nil; sub = sub.Next() {
		// Immediately send event to WebSocket users.
		ws := sub.Value.(Subscriber).Conn
		if ws != nil {
			if ws.WriteMessage(websocket.TextMessage, data) != nil {
				// User disconnected.
				unsubscribe <- sub.Value.(Subscriber).Name
			}
		}
	}
}
